import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store/modules/user';
import { useMenuStore } from '@/store/modules/menu';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { baseRoutes } from './modules/base';
import { appRoutes } from './modules/app';

import { generateDynamicRoutes } from './dynamicRouter';
import Cookies from 'js-cookie';
// 配置NProgress
NProgress.configure({ showSpinner: false });

// 静态路由
export const constantRoutes: RouteRecordRaw[] = [
  ...baseRoutes,
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue'),
    meta: { title: '登录', isHidden: true }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/home/404.vue'),
    meta: { title: '404', isHidden: true }
  }
];

// 异步路由,在这里动态添加各种路由
export const asyncRoutes: RouteRecordRaw[] = [
  ...appRoutes,
  // 404页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404', meta: { isHidden: true } }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  scrollBehavior: () => ({ left: 0, top: 0 })
});

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start();

  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title}` : '智航';

  const userStore = useUserStore();
  const menuStore = useMenuStore();
  const token = userStore.token || localStorage.getItem('token') || Cookies.get('token');

  // 如果有token
  if (token) {
    if (to.path === '/login') {
      // 如果已登录，重定向到首页
      next({ path: '/' });
      NProgress.done();
    } else {
      if (!userStore.hasGetMenus) {
        try {
          // 获取动态路由
          const accessRoutes = await generateDynamicRoutes();

          // 添加动态路由到路由实例
          accessRoutes.forEach(route => {
            router.addRoute(route);
          });

          // 设置已获取菜单标志
          userStore.setHasGetMenus(true);

          // 设置用户路由
          userStore.setRoutes([...baseRoutes, ...accessRoutes]);

          // 如果是根路径，重定向到工作台
          if (to.path === '/') {
            menuStore.setCollapse(false);
            if (accessRoutes.length > 0) {
              menuStore.setActiveMenu(accessRoutes[0].path);
              next({ path: accessRoutes[0].path, replace: true });
            } else {
              menuStore.setActiveMenu('/');
              next({ path: '/', replace: true });
            }
          } else {
            // 设置菜单高亮为当前路径
            menuStore.setActiveMenu(to.path);
            next({ ...to, replace: true });
          }
        } catch (error) {
          next('/login');
        }
      } else {
        // 菜单已获取，直接导航
        menuStore.setActiveMenu(to.path);
        next();
      }
    }
  } else {
    // 如果没有token，跳转到登录页
    if (to.path === '/login') {
      next();
    } else {
      next('/login');
    }
    NProgress.done();
  }
});

router.afterEach(to => {
  // 结束进度条
  NProgress.done();

  // 更新菜单激活状态
  const menuStore = useMenuStore();
  menuStore.setActiveMenu(to.path);
});

export default router;
